<style lang='scss'>
    .bag-fff{
        background-color: #fff;
    }
    .font-14{
        font-size: 14px;
    }
    .font-28{
        font-size: 28px;
    }
    .font-icon{
        font-size: 60px;

    }
    .padding-box{
        padding: 10px 15px;
    }
    .jumptitle{
        font-size: 14px;
        font-weight: bold;
        margin-left: 5px;
        color:#333;
    }
    .right-box{
        font-size:18px;font-weight:bold;border-bottom:1px solid #e5e5e5;padding-top:10px;padding-bottom:3px;padding-left:10px;
    }
    .home-card{
        // border: 1px solid #ededed;
        // box-shadow: 3px 5px 4px #c7c7c7;
        // border-radius: 5px;
        .border-box{
            border-radius: 5px;
            margin-top: 5px;
            height: 100px;
            background-color: #fff;
            .litTitleBox{
                font-size: 14px;
                color: #666;
            }
        }

    }
</style>



<template>
    <section class="home-main clearfix">
        <div style="text-align:right;margin-top:20px;">
            <div class="ivu-date-picker" >
                <DatePicker type="daterange"
                        class="margin-right-10"
                        placement="bottom-end"
                        placeholder="选择时间"
                        style="width:220px;"
                        :value="getshipdate"
                        @on-change="handleChange"
                ></DatePicker>
            </div>
            <div class="ivu-radio-group">
                <RadioGroup v-model="defaultdate" type="button" @on-change="changedate(defaultdate)">
                    <Radio v-for="(item,index) in dateList" :key="index" :label="index">{{item.label}}</Radio>
                </RadioGroup>
                <Tooltip>
                    <Icon type="ios-help-circle" style="color:#66b1ff;"></Icon>
                    <template #content max-width="150">
                        <p style="white-space: normal;width:150px">近一周、一月、三个月分别对应7天、30天、90天，从当期日期往前推对应的天数</p>
                    </template>
                </Tooltip>
            </div>
            <Button class="margin-left-10" type="primary" @click="getHomeData">查询</Button>
        </div>
        <div class="home-card clearfix margin-top-10">
            <Row>
                <Col span="6" >
                    <div class="border-box padding-box margin-right-10">
                        <div class="litTitleBox">面单总量 <Tooltip class="pull-right">
                            <!-- <Icon type="ios-help-outline"></Icon> -->
                            <Icon type="ios-help-circle" style="color:#66b1ff;"></Icon>
                            <!-- <div slot="content" style="white-space: normal">
                                <p>当前选择日期内订单数量总和</p>
                            </div> -->
                            <template #content >
                                <p>当前选择日期内订单数量总和</p>
                            </template>
                        </Tooltip></div>
                        <div class="height-90">
                            <div class="font-28 font-bold">{{orderData.total}}</div>
                            <div style="color:#999;">
                                同比 <span v-if="nowpreCycle>-1" class="margin-left-15 margin-right-15 font-14" style="color:#19be6b;">
                                        <Icon style="margin-right:5px" type="android-arrow-dropup"></Icon>{{nowpreDate.toFixed(2)}}%
                                    </span>
                                    <span v-else class="margin-left-15 margin-right-15 font-14" style="color:#ed3f14;">
                                        <Icon style="margin-right:5px" type="android-arrow-dropdown"></Icon>{{nowpreDate.toFixed(2)}}%
                                    </span>
                                环比 <span v-if="nowpreCycle>-1" class="margin-left-15 font-14" style="color:#19be6b;">
                                        <Icon style="margin-right:5px" type="android-arrow-dropup"></Icon>{{nowpreCycle.toFixed(2)}}%
                                    </span>
                                    <span v-else class="margin-left-15 font-14" style="color:#ed3f14;">
                                        <Icon style="margin-right:5px" type="android-arrow-dropdown"></Icon>{{nowpreCycle.toFixed(2)}}%
                                    </span>
                            </div>
                        </div>
                    </div>
                </Col>
                <Col span="6" >
                    <div class="border-box padding-box margin-right-5">
                        <div class="litTitleBox">余额 (USD)</div>
                        <div class="height-90">
                            <div class="font-28 font-bold">{{priceData.amount || 0}}</div>
                        </div>
                    </div>
                </Col>
                <Col span="6" >
                    <div class="border-box padding-box margin-left-5">
                        <div class="litTitleBox">余额可用天数 <Tooltip class="pull-right">
                            <!-- <Icon type="ios-help-outline"></Icon> -->
                            <Icon type="ios-help-circle" style="color:#66b1ff;"></Icon>
                            <template #content >
                                <p>根据最近7天面单金额的平均值计算</p>
                            </template>
                        </Tooltip></div>
                        <div class="height-90">
                            <div class="font-28 font-bold">{{priceData.days || 0}}</div>
                        </div>
                    </div>
                </Col>
                <Col span="6" >
                    <div class="border-box padding-box margin-left-10">
                        <div class="litTitleBox">待上网订单 <Tooltip class="pull-right" placement="left">
                            <Icon type="ios-help-circle" style="color:#66b1ff;"></Icon>
                            <template #content >
                                <p style="white-space: normal;width:100px">当前选择日期内物流状态为初始化的订单数量总和</p>
                            </template>
                        </Tooltip></div>
                        <div class="height-90">
                            <div class="font-28 font-bold">{{orderData.unknown}}</div>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <div class="clearfix margin-top-10">
            <Row>
                <Col span="12" >
                    <div class="bag-fff" style="margin-right:5px;">
                        <div id="pieGraph" style="height: 350px;width:100%"></div>
                    </div>
                </Col>
                <Col span="12">
                    <div class="bag-fff" style="margin-left:5px;height:350px">
                        <div class="right-box" style="color:#666">快捷访问</div>
                        <div style="display:flex;padding:15px;30px">
                            <router-link style="flex:1" :to="{'name':'labelAdd'}">
                                <div ><span style="color:#2d8cf0;font-size:60px" class="iconfont icon-huozhuduanwodeyundan"></span><div class="jumptitle">创建运单</div></div>
                            </router-link>
                            <router-link  style="flex:1" :to="{'name':'label'}">
                                <div ><span style="color:#2d8cf0;font-size:60px" class="iconfont icon-yundanguanli"></span><div class="jumptitle">运单记录</div></div>
                            </router-link>
                            <router-link style="flex:1" :to="{'name':'calculate'}">
                                <div ><span style="color:#ff9900;font-size:60px" class="iconfont icon-yundanmingxitongji"></span><div class="jumptitle">运费测算</div></div>
                            </router-link>
                        </div>
                        <div style="display:flex;padding:15px;30px">
                            <router-link style="flex:1" :to="{'name':'transaction'}">
                                <div ><span style="color:#ff9900;font-size:60px" class="iconfont icon-jiaoyijilu"></span><div class="jumptitle">交易记录</div></div>
                            </router-link>
                            <router-link style="flex:1" :to="{'name':'freeze'}">
                                <div ><span style="color:#ff9900;font-size:60px" class="iconfont icon-dongjie"></span><div class="jumptitle">冻结记录</div></div>
                            </router-link>
                            <router-link style="flex:1" :to="{'name':'addressShipper'}">
                                <div><span style="color:#2d8cf0;font-size:60px" class="iconfont icon-dizhibu"></span><div class="jumptitle">发货地址</div></div>
                            </router-link>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <div class="bag-fff clearfix margin-top-10" style="position:relative">
            <Row>
            <Col span="24">
                <div id="lineGraph" style="height: 350px;width:100%"></div>
            </Col>
            </Row>
        </div>
    </section>
</template>

<script>
import { HttpGetHomeData } from "@/service/accountbill";
let echarts = require('echarts');

// require('echarts/lib/chart/line');
// require('echarts/lib/chart/pie');
// // 引入提示框和标题组件
// require('echarts/lib/component/grid');
// require('echarts/lib/component/polar');
// require('echarts/lib/component/tooltip');
// require('echarts/lib/component/title');
// require('echarts/lib/component/legend');
// require('echarts/lib/component/markPoint');
// require('echarts/lib/component/markLine');

export default {
    data(){
        return {
            dateList:[
                {label:"近一周",value:1},
                {label:"近一月",value:2},
                {label:"近三月",value:3},
            ],
            defaultdate:0,
            getshipdate:[],
            pieList:[],
            orderData:{},
            priceData:{},
            datetype:1,
            nowpreDate:0,
            nowpreCycle:0,
        }
    },
    created(){
        this.getChooseDays();
        this.getHomeData();

    },
    methods:{
        getChooseDays(){
            let beginDate  = this.getDay(-7)
            let endDate = this.getDay(0)
            this.getshipdate = [beginDate,endDate]
            return true

        },
        getDay(day){
            var today = new Date();
            var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
            today.setTime(targetday_milliseconds); //注意，这行是关键代码
            var tYear = today.getFullYear();
            var tMonth = today.getMonth();
            var tDate = today.getDate();
            tMonth = this.doHandleMonth(tMonth + 1);
            tDate = this.doHandleMonth(tDate);
            return tYear+"-"+tMonth+"-"+tDate;
        },
        doHandleMonth(month){
            var m = month;
            if(month.toString().length == 1){
                m = "0" + month;
            }
            return m;
        },
        changedate(val){
            // console.log(val)
            if(val==0){
                this.getChooseDays()
            }else if(val==1){
                let beginDate  = this.getDay(-30)
                let endDate = this.getDay(0)
                this.getshipdate = [beginDate,endDate]
            }else{
                let beginDate  = this.getDay(-90)
                let endDate = this.getDay(0)
                this.getshipdate = [beginDate,endDate]
            }
        },
        getBetweenDays(strDateStart, strDateEnd) {
            var strSeparator = "-";
            //日期分隔符
            var oDate1;   var oDate2;
            var iDays;
            oDate1 = strDateStart.split(strSeparator);
            oDate2 = strDateEnd.split(strSeparator);
            var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
            var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
            iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24)
            //把相差的毫秒数转换为天数
            return iDays;
        },
        handleChange(value){
            // console.log(value)
            if(value[0] == '' || value[1] =='') return
            // let arrdate1 = new Date(value[0])
            // let arrdate2 = new Date(value[1])
            // let itemdate = arrdate2.getTime() - arrdate1.getTime()
            let daynum = this.getBetweenDays(value[0],value[1])
            // console.log(daynum)
            if( Number(daynum) > 90 ){
                this.getshipdate = [value[0],value[1]]
                // console.log(Number(daynum))
                this.datetype = 0
            }else{
                let beginDate = value[0]
                let endDate = value[1]
                this.getshipdate = [beginDate,endDate]
                // this.getpeding()
            }
        },
        compareFN(arr,property) {//比较日期大小函数
            // console.log(arr)
            var i = 0;
            var j = 0;
            let t;
            for ( i = 0; i < arr.length; i++){
                for (j = 0; j < arr.length; j++){
                    let oDate1 = new Date(arr[i][property]);
                    let oDate2 = new Date(arr[j][property]);
                    if (oDate1.getTime() < oDate2.getTime()){
                        t = arr[i];
                        arr[i] = arr[j];
                        arr[j] = t;
                    }
                }
            }
            return arr
        },
        async getHomeData(){

            let args1 = {
                start_at:this.getshipdate[0],
                end_at:this.getshipdate[1]
            }
            let args2 = {
                start_at:this.getshipdate[0],
                end_at:this.getshipdate[1],
                type:this.datetype,
                orgId:1,
            }
            HttpGetHomeData({
                component_id:9,
                args:JSON.stringify(args1)
            }).then(res=>{
                this.orderData = res.data.data[0];
                this.nowpreDate = this.orderData.preDate > 0 ? ((this.orderData.total - this.orderData.preDate)/this.orderData.preDate)*100 : 0
                this.nowpreCycle = this.orderData.preCycle > 0 ? ((this.orderData.total - this.orderData.preCycle)/this.orderData.preCycle)*100 : 0
            },err=>{

            })
            HttpGetHomeData({
                component_id:10,
                args:JSON.stringify(args1)
            }).then(res=>{
                this.priceData = res.data.data[0];
            },err=>{

            })
            this.pieList = [];
            HttpGetHomeData({
                component_id:11,
                args:JSON.stringify(args1)
            }).then(res=>{
                res.data.data.map((item)=>{
                    let json = {
                        name:item.shipper_state,
                        value:item.total
                    }
                    this.pieList.push(json)
                });
                this.drawPie();
            },err=>{

            })
            HttpGetHomeData({
                component_id:12,
                args:JSON.stringify(args2)
            }).then(res=>{
                // this.handlelineData(res.data);
                this.handlelineDataMonth(res.data);
            },err=>{

            })

        },
        drawPie(){
            // 自定义颜色
            let colorList = ['#00BFFF','#FFD700','#48D1CC','#FF4500','#C0C0C0','#FF00FF','#F4A460'];
            let pieGraph = echarts.init(document.getElementById('pieGraph'));
            let titles = this.pieList.map(item=>{
                return item.name
            })
            let pieData = this.pieList.map(item=>{
                return item.total
            })
            // console.log(this.pieList,titles)
            pieGraph.setOption({
                title : {
                    text: '州发货排名Top5',
                    x:'center',
                    top:10,
                    textStyle: {
                        color: "#666666",
                    },
                    subtextStyle: {
                        color: "#999999",
                    },
                },
                tooltip : {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: titles
                },
                color:colorList,
                series : [
                    {
                        name: '州名',
                        type: 'pie',
                        radius : ['45%','70%'],
                        center: ['50%', '60%'],
                        data: this.pieList,
                        itemStyle: {
                            // borderWidth:5,
                            // borderColor:'#fff',
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)',
                            }
                        }
                    }
                ]
            })
            window.addEventListener("resize", () => {
                    if(pieGraph){
                        pieGraph.resize()
                    }
            })
        },
        // 根据选择开始结束日期获取中间日期
        getAlldate(day1,day2){
            var getDate = function (str){
                var tempDate = new Date();
                var list = str.split("-");
                tempDate.setFullYear(list[0]);
                tempDate.setMonth(list[1] - 1);
                tempDate.setDate(list[2]);
                return tempDate;
            }
            var date1 = getDate(day1);
            var date2 = getDate(day2);
            if (date1 > date2) {
                var tempDate = date1;
                date1 = date2;
                date2 = tempDate;
            }
            date1.setDate(date1.getDate() + 1);
            var dateArr = [];
            var i = 0;
            while (!(date1.getFullYear() == date2.getFullYear()
                    && date1.getMonth() == date2.getMonth() && date1.getDate() == date2
                    .getDate())) {
                    var dayStr =date1.getDate().toString();
                    if(dayStr.length ==1){
                        dayStr="0"+dayStr;
                    }
                dateArr[i] = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-"
                        + dayStr;
                i++;
                date1.setDate(date1.getDate() + 1);
            }
            dateArr.splice(0,0,day1)
            dateArr.push(day2);
            return dateArr;
        },
        // 根据给了一些日期，自动补全剩余的
        handlelineData(res){
            // console.log(res)
            let arr1 = [],arr2 = [],arr3 = [],arr5 = [],arr6 =[];
            res.data.map(item=>{
                if(item.carrier == 'FedEx'){
                    arr1.push(item);
                }else{
                    arr2.push(item);
                }
            })

            arr1.map(item=>{
                arr2.map(json=>{
                    if((new Date(item.date)) - (new Date(json.date)) == 0){
                        let dataone = {
                            carrier1: item.carrier || 'FedEx',
                            qty1: item.qty || 0,
                            carrier2: json.carrier || 'UPS',
                            qty2: json.qty || 0,
                            date:item.date
                        }
                        arr3.push(dataone)
                    }
                })
            })
            // console.log(arr1,arr2,arr3)
            arr1.map((item,index)=>{
                arr3.map(json=>{
                    if((new Date(item.date)) - (new Date(json.date))==0){
                        arr5.push(index)
                    }
                })
            })
            arr2.map((item,index)=>{
                arr3.map(json=>{
                    if((new Date(item.date)) - (new Date(json.date))==0){
                        arr6.push(index)
                    }
                })
            })
            let aArr = arr1.filter((item,index)=>{
                return arr5.indexOf(index) == -1
            })
            let bArr = arr2.filter((item,index)=>{
                return arr6.indexOf(index) == -1
            })
            // console.log(aArr,bArr)
            aArr.map(item=>{
                let dataone = {
                    carrier1: item.carrier || 'FedEx',
                    qty1: item.qty || 0,
                    carrier2: 'UPS',
                    qty2: 0,
                    date:item.date
                }
                arr3.push(dataone)
            })
            bArr.map(item=>{
                let dataone = {
                    carrier1: 'FedEx',
                    qty1: 0,
                    carrier2: item.carrier || 'UPS',
                    qty2: item.qty || 0,
                    date:item.date
                }
                arr3.push(dataone)
            })
            let arr3date=[];
            arr3.map(item=>{
                arr3date.push(item.date)
            })
            let rangeDate = this.getAlldate(this.getshipdate[0],this.getshipdate[1]);
            let cDatalist = rangeDate.filter(item=>{
                return arr3date.indexOf(item) == -1
            })
            // console.log(arr3date,cDatalist)
            cDatalist.map(item=>{
                let dataone = {
                    carrier1: 'FedEx',
                    qty1: 0,
                    carrier2: 'UPS',
                    qty2: 0,
                    date:item
                }
                arr3.push(dataone)
            })

            let newArr = this.compareFN(arr3,'date')
            this.drawLine(newArr);
        },
        // 全部日期都给过来/根据月份展示
        handlelineDataMonth(res){
            let arr1 = [],arr2 = [],arr3 = [];
            res.data.map(item=>{
                if(item.carrier == 'FedEx'){
                    arr1.push(item);
                }else{
                    arr2.push(item);
                }
            })

            arr1.map(item=>{
                arr2.map(json=>{
                    if((new Date(item.date)) - (new Date(json.date)) == 0){
                        let dataone = {
                            carrier1: item.carrier || 'FedEx',
                            qty1: item.qty || 0,
                            carrier2: json.carrier || 'UPS',
                            qty2: json.qty || 0,
                            date:item.date
                        }
                        arr3.push(dataone)
                    }
                })
            })
            this.drawLine(arr3);

        },
        drawLine(datalist){
            let lineGraph = echarts.init(document.getElementById('lineGraph'));
            var colors = ['#00BFFF', '#F4A460', '#675bba'];

            let arrdate=[],fedexdata=[],upsdata=[];
            datalist.map(item=>{
                fedexdata.push(item.qty1)
                upsdata.push(item.qty2)
                arrdate.push(item.date)
            })
            // console.log(arrdate,fedexdata,upsdata)
            // 绘制图表
            lineGraph.setOption({
                title: {
                    text: '销售额统计',
                    left: 'center',
                    top:10,
                    textStyle: {
                        color: "#666666",
                    },
                    subtextStyle: {
                        color: "#999999",
                    },
                },
                legend: {
                    left: 'center',
                    data: ['FedEx', 'UPS'],
                    top:40
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
                    },
                },

                xAxis:
                {
                    data: arrdate
                },
                yAxis: {
                    type: 'value',
                },
                grid: {
                    top: '25%',
                    left: '3%',
                    right: '3%',
                    containLabel: true
                },
                color:colors,
                series: [
                    {
                        name:"FedEx",
                        type:'line',
                        data: fedexdata
                    },
                    {
                        name:"UPS",
                        type:'line',
                        data: upsdata
                    }
                ]
            })
            window.addEventListener("resize", () => {
                if(lineGraph){
                    lineGraph.resize()
                }
            })
        },

    },

};
</script>
